package com.lv.suyiyong.hfrwork.ui

import android.content.Intent
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.LogUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lv.common.base.BaseActivity
import com.lv.common.im.GenerateTestUserSig
import com.lv.common.im.push.OfflineMessageDispatcher
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.showToast
import com.lv.service.bean.FindProsBean
import com.lv.service.event.HomeTabChangeEvent
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.utils.YgxToolsKt
import com.lv.suyiyong.hfrwork.R
import com.lv.suyiyong.hfrwork.YgxApplication
import com.lv.suyiyong.hfrwork.databinding.ActivityHomeBinding
import com.lv.suyiyong.hfrwork.moudel.MainPageViewModel
import com.lv.suyiyong.hfrwork.moudel.MainViewModel
import com.lv.suyiyong.hfrwork.widget.HomeBottomTabWidget
import com.tencent.imsdk.v2.V2TIMConversationListener
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMValueCallback
import com.tencent.qcloud.tuicore.util.SPUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel


@Route(path = ARoutUtils.HomeActivityURL)
class HomeActivity : BaseActivity<ActivityHomeBinding>() {
    @Autowired(name = "userInfo")
    @JvmField
    var mUserInfo: UserInfo? = null

    @Autowired(name = "tabId")
    @JvmField
    var mTabId: Int = 0
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private val pageViewModel by viewModels<MainPageViewModel>()

    private val viewModel: MainViewModel by viewModel()
    private val serviceViewModel: ServiceViewModel by viewModel()
    override fun getLayoutRes() = R.layout.activity_home
    override fun initView() {
        super.initView()
        YgxApplication.getInstance().init(GenerateTestUserSig.SDKAPPID)
        YgxApplication.getInstance().registerPushManually()
        ARouter.getInstance().inject(this)
    }

    override fun initData() {
        super.initData()
        doWorkManager()
        UserDbHelper.getLiveUserInfo(this).observeKt { userInfo ->
            if (userInfo != null && !userInfo.id.isNullOrEmpty()) {
                sendIMToken(userInfo.phone)
            }
        }
    }

    private fun sendIMToken(phone: String?) {
//        val userphone = phone ?: ""
//        val token = SPUtils.getInstance().getString("im_register", "")
//        val appVersionCode = AppUtils.getAppVersionName()
//        val brand = DeviceUtils.getManufacturer()
//        LogUtils.e("aaa")
//        lifecycleScope.launchWhenCreated {
//            val imMap = mutableMapOf<String, String>(
//                "phone" to userphone,
//                "plat" to brand,
//                "sion" to appVersionCode,
//                "code" to "2",
//                "ptoken" to token,
//            )
//            val result: DataResult<BaseYgxRsp> =
//                myScope.async { viewModel.saveTX(imMap) }.await()
//        }
    }

    /**
     * 执行后台任务
     */
    private fun doWorkManager() {
//        YgxToolsKt.doWorkManager(this)
    }

    override fun initConfig() {
        super.initConfig()
        pageViewModel.setPage(mTabId)
        mBinding.homeBottomTab.init(supportFragmentManager, pageViewModel)
        initUnreadCount()
//        findPros()
    }

    private fun findPros() {
        startLoading()
        val map = mutableMapOf<String, String>(
            "telAddress" to "1",
            "spuCategory" to "1",
            "telCategory" to "1",
            "professional" to "1",//查所有业务员
            "issuer" to "1",//查所有发行人员
        )
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.findPros(map) }.await()
            parseFindProsResult(result)
        }
    }

    private fun parseFindProsResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<FindProsBean> { code, data, message, result ->
                data?.let {

                    lifecycleScope.launch {
                        //地址信息
                        this.launch {
                            val addressList = it.address
                            if (addressList != null) {
                                YgxToolsKt.saveAddressRoom(this@HomeActivity, addressList)
                            }
                        }
                    }
                }

            }
            onBizError<Any> { code, message, data ->
                showToast(message)
            }
        }
        data.onFailure {
            LogUtils.e("eee")
        }
    }


    private fun initUnreadCount() {
        V2TIMManager.getConversationManager()
            .getTotalUnreadMessageCount(object : V2TIMValueCallback<Long?> {
                override fun onSuccess(aLong: Long?) {
                    val unreadCount = aLong ?: 0
                    setUnReadMessageCount(unreadCount)

                }


                override fun onError(code: Int, desc: String) {
                    LogUtils.e("imsdk", "failure, code:$code, desc:$desc")
                }
            })
        V2TIMManager.getConversationManager()
            .addConversationListener(object : V2TIMConversationListener() {
                // 收到所有会话的未读总数变更通知
                override fun onTotalUnreadMessageCountChanged(totalUnreadCount: Long) {
                    super.onTotalUnreadMessageCountChanged(totalUnreadCount)
                    setUnReadMessageCount(totalUnreadCount)
                }
            })


    }

    private fun setUnReadMessageCount(unreadCount: Long) {
        var unreadStr = "" + unreadCount
        if (unreadCount > 100) {
            unreadStr = "99 +"
        }
        mBinding.homeBottomTab.setMessageCount(unreadStr)
        // update Huawei offline push Badge
        OfflineMessageDispatcher.updateBadge(this@HomeActivity, unreadCount.toFloat().toInt())
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
    }

    override fun onResume() {
        super.onResume()
        val page = pageViewModel.getPage() ?: 0
        initToolBar(page)
    }

    override fun initEvents() {
        super.initEvents()
        rigestEventBus()
        mBinding.homeBottomTab.setOnTabPagerListener(object : HomeBottomTabWidget.TabPagerListener {
            override fun OnClickTab(position: Int) {
                initToolBar(position)
            }
        })
    }

    private fun initToolBar(page: Int) {
        when (page) {
            0 -> {
                initStatusBar(this, true, false)
            }

            else -> {
                initStatusBar(this, true, true)
            }
        }
    }

    private fun rigestEventBus() {
        LiveEventBus.get(
            HomeTabChangeEvent::class.java,
        ).observe(
            this
        ) { s ->
            if (s != null) {
                val tab = s.tab
                mTabId = tab
                changeHomeTab()
            }
        }
    }

    private fun changeHomeTab() {
        pageViewModel.setPage(mTabId)
        mBinding.homeBottomTab.init(supportFragmentManager, pageViewModel)
    }

    override fun onBackPressed() {
        super.onBackPressed()
//        exitProcess(0)
        moveTaskToBack(true)

    }

//    private var exitTime: Long = 0
//
//    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            exit()
//            return false
//        }
//        return super.onKeyDown(keyCode, event)
//    }
//
//    private fun exit() {
//        if (System.currentTimeMillis() - exitTime > 2000) {
//            showToast("再按一次退出程序")
//            exitTime = System.currentTimeMillis()
//        } else {
//            exitProcess(0)
//        }
//    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            return
        }
        if (supportFragmentManager.fragments.size > 0) {
            val fragments = supportFragmentManager.fragments
            for (fragment in fragments) {
                fragment.onActivityResult(requestCode, resultCode, data)
            }
        }
//        if (resultCode == RESULT_OK) {
//            when (requestCode) {
//                0 -> {
//
//                }
//            }
//        }

    }

    override fun onDestroy() {
        super.onDestroy()

    }
}